﻿using AutoMapper;
using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.UI;
using H2.NET.Web.Management.Config.Service;
using System.Data;
using H2.NET.Web.Workflow;

namespace H2.NET.Web.Pages.SMD
{
    public partial class Transfer : BasePage
    {
        public List<v_DeviceDeposit> devices = new List<v_DeviceDeposit>();
        public string deviceCheckes = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            uc_store_info1.Title = "要转出的门店";
            uc_store_info1.IsShowDeivceList = false;
            uc_store_info2.Title = "要转入的门店";
            uc_store_info2.IsShowDeivceList = false;
            DwzAssessment1.Category = "Transfer";
            btn_submit.Visible = TaskAPI.IsAllowSubmit;
            uc_store_info1.AllRegion = "True";
            uc_store_info2.AllRegion = "True";
            if (!IsPostBack)
            {
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.tip('" + string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser) + "', 'info');", true);
                    return;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                #region Submit Data


                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);

                if (TaskAPI.Step == "Submit Data")
                {
                    if (ass != null)
                    {
                        var afterStoreId = "";
                        var beforStoreId = "";

                        var currentChangelogs = (t_StoreDataChangeLog._AssessmentID == ass.ID).List<t_StoreDataChangeLog>();
                        if (currentChangelogs != null)
                        {
                            foreach (t_StoreDataChangeLog log in currentChangelogs)
                            {
                                if (log.FieldName.Equals("StoreID"))
                                {
                                    afterStoreId = log.AfterValue;
                                    beforStoreId = log.BeforeValue;
                                }
                                deviceCheckes += log.DataID + ",";
                            }
                            uc_store_info1.store = (t_smd_Store._StoreID == beforStoreId).ListFirst<t_smd_Store>(Storage.Context3);
                            hf_out_storeId.Value = beforStoreId;
                            rpt_devices.DataSource = (v_DeviceDeposit._StoreID == beforStoreId).List<v_DeviceDeposit>(Storage.Context3);
                            rpt_devices.DataBind();
                            uc_store_info2.store = (t_smd_Store._StoreID == afterStoreId).ListFirst<t_smd_Store>(Storage.Context3);
                            hf_in_storeId.Value = afterStoreId;
                        }
                    }
                    const string sOutid = "outid";
                    const string sInid = "inid";

                    var outid = AksRequest.GetQueryInt(sOutid);
                    var inid = AksRequest.GetQueryInt(sInid);

                    var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");
                    if (!string.IsNullOrEmpty(blankVlue))
                    {
                        var arr = blankVlue.Split('|');
                        outid = Convert.ToInt32(arr[1]);
                        inid = Convert.ToInt32(arr[2]);
                    }

                    if (outid > 0)
                    {
                        uc_store_info1.store = (t_smd_Store._StoreID == outid).ListFirst<t_smd_Store>(Storage.Context3);
                        hf_out_storeId.Value = outid.ToString();
                        devices = (v_DeviceDeposit._StoreID == outid).List<v_DeviceDeposit>(Storage.Context3).ToList();
                        rpt_devices.DataSource = devices;
                        rpt_devices.DataBind();
                    }
                    if (inid > 0)
                    {
                        uc_store_info2.store = (t_smd_Store._StoreID == inid).ListFirst<t_smd_Store>(Storage.Context3);
                        hf_in_storeId.Value = inid.ToString();
                    }

                    uc_store_info1.StrId = inid > 0 ? (sInid + "=" + inid + "&" + sOutid) : sOutid;
                    uc_store_info1.IsCanEditAuthID = true;

                    uc_store_info2.StrId = outid > 0 ? (sOutid + "=" + outid + "&" + sInid) : sInid;
                    uc_store_info2.IsCanEditAuthID = true;

                    if (devices.Count == 0)
                    {
                        uc_store_info2.Visible = false;
                        btn_submit.Visible = false;
                        tr_depositChange.Visible = false;
                        if (outid > 0)
                        {
                            JsTip(string.Format("该门店没有设备，无法发起三方转移。"));
                            return;
                        }
                    }
                    else
                    {
                        tb_noDevice.Visible = false;
                    }

                    if (!String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        assessment.Visible = true;
                    }

                }
                #endregion

                #region 审批环节
                else
                {
                    var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                    if (storeMasterData == null)
                    {
                        btn_submit.Visible = false;
                        JsTip("加载数据失败，请关闭页面重新打开！");
                        return;
                    }

                    hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                    hl_ExportPdf.Visible = true;

                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");
                    cb_DepositConfiscated.Checked = storeMasterData.PcModel == "True";

                    tb_noDevice.Visible = false;
                    assessment.Visible = true;

                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        var blankVlue = ((object[])TaskAPI["BlankVlue"])[0].ToString();
                        var val = blankVlue.Split('|');
                        var deviceIds = val[0];
                        var outStoreId = val[1];
                        var inStoreId = val[2];
                        hf_in_storeId.Value = inStoreId;
                        const string sOutid = "outid";
                        const string sInid = "inid";
                        var outid = AksRequest.GetQueryInt(sOutid);
                        var inid = AksRequest.GetQueryInt(sInid);
                        deviceCheckes = deviceIds;
                        if (outid > 0)
                        {
                            outStoreId = outid.ToString();
                        }
                        if (inid > 0)
                        {
                            inStoreId = inid.ToString();
                            hf_in_storeId.Value = inid.ToString();
                        }
                        uc_store_info1.StrId = Utils.StrToInt(inStoreId, 0) > 0 ? (sInid + "=" + inid + "&" + sOutid) : sOutid;
                        uc_store_info1.IsCanEditAuthID = false;

                        uc_store_info2.StrId = Utils.StrToInt(outStoreId, 0) > 0 ? (sOutid + "=" + outid + "&" + sInid) : sInid;
                        uc_store_info2.IsCanEditAuthID = true;
                        uc_store_info1.store = (t_smd_Store._StoreID == outStoreId).ListFirst<t_smd_Store>(Storage.Context3);
                        uc_store_info2.store = (t_smd_Store._StoreID == inStoreId).ListFirst<t_smd_Store>(Storage.Context3);
                        hf_out_storeId.Value = uc_store_info1.store.StoreID.ToString();
                        rpt_devices.DataSource = (v_DeviceDeposit._StoreID == uc_store_info1.store.StoreID).List<v_DeviceDeposit>(Storage.Context3).ToList();
                        rpt_devices.DataBind();

                        tb_DeviceEapproveSN.Text = storeMasterData.DeviceEapproveSN;
                    }
                    else
                    {

                        uc_store_info1.IsCanEditAuthID = uc_store_info2.IsCanEditAuthID = false;

                        var blankVlue = ((object[])TaskAPI["BlankVlue"])[0].ToString();
                        var val = blankVlue.Split('|');
                        var deviceIds = val[0];
                        var outStoreId = val[1];
                        var inStoreId = val[2];

                        uc_store_info1.store = (t_smd_Store._StoreID == outStoreId).ListFirst<t_smd_Store>(Storage.Context3);
                        uc_store_info2.store = (t_smd_Store._StoreID == inStoreId).ListFirst<t_smd_Store>(Storage.Context3);

                        rpt_devices.DataSource = (v_DeviceDeposit._DeviceID.In(deviceIds.Split(','))).List<v_DeviceDeposit>(Storage.Context3).ToList();
                        rpt_devices.DataBind();

                        cb_DepositConfiscated.Visible = false;
                        cb_DepositConfiscated.Checked = storeMasterData.PcModel == "True";
                        tb_DeviceEapproveSN.Visible = false;
                        l_DepositConfiscated.Text = storeMasterData.PcModel == "True" ? "是" : "否";
                        l_DeviceEapproveSN.Text = storeMasterData.DeviceEapproveSN;
                    }
                    #region 审批项初始化
                    switch (TaskAPI.Step)
                    {
                        case "Data Check":

                            DwzAssessment1.Category = "Transfer";
                            break;
                        case "Manager Approve":

                            DwzAssessment1.Category = "Transfer";
                            break;
                        case "DMO Commit":
                            TaskAPI.Summary = "DMO导入核查 / " + TaskHelper.getSummary(TaskAPI.Summary);
                            DwzAssessment1.Category = "Transfer";
                            break;
                    }
                    #endregion
                }
                #endregion
            }
        }


        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                var deviceIds = storeMasterData.DispenseModel;  // 选择的设备id
                var outStoreId = storeMasterData.MallName;      // 转出的门店id
                var inStoreId = storeMasterData.MallShortName;  // 转入的门店id

                uc_store_info1.IsCanEditAuthID = uc_store_info2.IsCanEditAuthID = false;
                uc_store_info1.store = StoreService.GetSmdStoreById(Utils.StrToInt(outStoreId, 0));
                uc_store_info2.store = StoreService.GetSmdStoreById(Utils.StrToInt(inStoreId, 0));

                rpt_devices.DataSource = (v_DeviceDeposit._DeviceID.In(deviceIds.Split(','))).List<v_DeviceDeposit>(Storage.Context3).ToList();
                rpt_devices.DataBind();

                cb_DepositConfiscated.Visible = false;
                l_DepositConfiscated.Text = storeMasterData.PcModel == "True" ? "是" : "否";
                l_DeviceEapproveSN.Text = storeMasterData.DeviceEapproveSN;

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;
                tb_DeviceEapproveSN.Visible = false;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string return_msg)
        {
            bool flag;
            try
            {
                var chDevice = AksRequest.GetString("ckDevice");
                #region 数据验证
                if (string.IsNullOrEmpty(chDevice) && TaskAPI.Step != "DMO Commit")
                {
                    return_msg = "请选择要转出的设备";
                    return false;
                }
                if (TaskAPI.Step == "Submit Data" && TaskAPI.IsAllowSubmit && !TaskAPI.Summary.Contains("退回")) // 如果是退回的情况，不存在验证
                {
                    if (!ajaxUpload1.IsHaveAttachment)
                    {
                        return_msg = "请上传E-approve/CRM审批截屏";
                        return false;
                    }

                    if (string.IsNullOrEmpty(hf_in_storeId.Value))
                    {
                        return_msg = "请选择要转出的设备";
                        return false;
                    }
                    if (string.IsNullOrEmpty(hf_out_storeId.Value))
                    {
                        return_msg = "请选择要转出设备的门店";
                        return false;
                    }
                    if (string.IsNullOrEmpty(chDevice))
                    {
                        return_msg = "请选择要转出的设备";
                        return false;
                    }

                    if (AksRequest.GetQueryIntValue("outid") == AksRequest.GetQueryIntValue("inid"))
                    {
                        return_msg = "转出与转入的门店不能选择同一个";
                        return false;
                    }

                    var devices = new List<int>();
                    devices.Add(Utils.StrToInt(chDevice, 0));
                    if (DeviceService.IsUnfinish(devices) && String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                    {
                        return_msg = "发现有设备其他业务流程中，请先完成其他流程。";
                        return false;
                    }
                }
                var outStoreid = hf_out_storeId.Value.ToString() == "" ? uc_store_info1.store.StoreID.ToString() : hf_out_storeId.Value.ToString();
                var blankVlue = ((object[])TaskAPI["BlankVlue"])[0].ToString();
                var val = blankVlue.Split('|');
                var deviceIds = val[0];
                var deviceid = chDevice == "" ? deviceIds : chDevice;
                var deviceDeposit =
                    (v_DeviceDeposit._StoreID == outStoreid & v_DeviceDeposit._DeviceID == deviceid)
                        .ListFirst<v_DeviceDeposit>(Storage.Context3);

                if (deviceDeposit != null && deviceDeposit.Amount > 0 && !cb_DepositConfiscated.Checked && (uc_store_info1.store.DealerID != uc_store_info2.store.DealerID))
                {
                    return_msg = "若有设备保证金，请勾选需发起保证金变更流程！";
                    return false;
                }


                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }

                }
                #endregion


                var _device = DeviceService.GetSmdDeviceById(Utils.StrToInt(chDevice, 0));
                var inStore = StoreService.GetSmdStoreById(uc_store_info2.store.StoreID);
                var outStore = StoreService.GetSmdStoreById(uc_store_info1.store.StoreID);
                var inDealer = DealerService.GetById(inStore.DealerID.Value);
                var outDealer = DealerService.GetById(outStore.DealerID.Value);

                var _DealerCode_in = inDealer.DealerCode != null ? inDealer.DealerCode.ToString() : "";
                var _DealerName_in = inDealer.Name != null ? inDealer.Name.ToString() : "";
                var _DealerCode_out = outDealer.DealerCode != null ? outDealer.DealerCode.ToString() : "";
                var _DealerName_out = outDealer.Name != null ? outDealer.Name.ToString() : "";
                //  var _summary = "-" + _device.FullSetSN + "-转入:" + inDealer.DealerCode+ " 转出:" + outDealer.DealerCode;
                var _summary = "-" + _device.FullSetSN + "-转入:" + _DealerCode_in + "(" + _DealerName_in + ")" + " 转出:" + _DealerCode_out + "(" + _DealerName_out + ")";

                #region 引擎传值
                if (TaskAPI.Step == "Submit Data")
                {
                    var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                    // 选择的设备id | 转出的门店id | 转入的门店id
                    TaskAPI["BlankVlue"] = chDevice + "|" + hf_out_storeId.Value + "|" + hf_in_storeId.Value;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI.Summary = "设备三方转移信息区域负责人确认 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                }
                else
                {
                    TaskAPI["ApproveResult"] = DwzAssessment1.Assessment.Opinion;
                    TaskAPI["TaskID"] = TaskAPI.TaskID;
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["BlankVlue"] = chDevice + "|" + hf_out_storeId.Value + "|" + hf_in_storeId.Value;
                        TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            //TaskAPI.Summary = "设备三方转移信息CSM审核 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                            TaskAPI.Summary = "设备三方转移信息CSM审核 / " + TaskHelper.getSummary(TaskAPI.Summary);
                        else
                            //TaskAPI.Summary = "(退回)填写设备三方转移信息 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                            TaskAPI.Summary = "(退回)填写设备三方转移信息 / " + TaskHelper.getSummary(TaskAPI.Summary);
                    }
                    else if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["BlankVlue"] = chDevice + "|" + hf_out_storeId.Value + "|" + hf_in_storeId.Value;
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            //TaskAPI.Summary = "DMO导入核查 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                            TaskAPI.Summary = "DMO导入核查 / " + TaskHelper.getSummary(TaskAPI.Summary);
                        else
                            //TaskAPI.Summary = "(退回)设备三方转移信息区域负责人确认 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                            TaskAPI.Summary = "(退回)设备三方转移信息区域负责人确认 / " + TaskHelper.getSummary(TaskAPI.Summary);
                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "0")
                            //TaskAPI.Summary = "(退回)设备三方转移信息CSM审核 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                            TaskAPI.Summary = "(退回)设备三方转移信息CSM审核 / " + TaskHelper.getSummary(TaskAPI.Summary);
                    }
                }

                #endregion

                #region 提交步骤

                var step = string.Empty;
                Storage.TransactionExecute(o =>
                {
                    #region 审批意见记录

                    var ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        if (storeMasterData == null)
                        {
                            storeMasterData = new t_StoreMasterData
                            {
                                SubmitDate = DateTime.Now,
                                Creator = TaskAPI.UserName,
                                ApplicationNO = uc_head1.applicationNo,
                                Process = TaskAPI.Process,
                                Incident = TaskAPI.Incident,
                                BusinessProcess = ass.BusinessProcess,
                                BusinessKey = ass.BusinessKey
                            };
                        }

                        // 是否涉及保证金罚没
                        storeMasterData.PcModel = cb_DepositConfiscated.Checked.ToString();
                        // 选择的设备id
                        storeMasterData.DispenseModel = chDevice;
                        // 转出的门店id
                        storeMasterData.MallName = hf_out_storeId.Value;
                        // 转入的门店id
                        storeMasterData.MallShortName = hf_in_storeId.Value;
                        // 系统流水号
                        storeMasterData.DeviceEapproveSN = tb_DeviceEapproveSN.Text;

                        Storage.Save(Storage.Context1, storeMasterData);

                        // 保存变更日志
                        var changelogs = SaveChangeLog(Utils.StrToInt(chDevice, 0), ass.ID);
                        Storage.Save(Storage.Context1, changelogs.ToArray());
                        BusinessService.SaveChildProcess(TaskAPI, ass, "active");

                        var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(chDevice, 0));
                        var stores = new List<t_smd_Store>();


                        stores.Add(StoreService.GetSmdStoreById(Utils.StrToInt(hf_out_storeId.Value, 0)));
                        stores.Add(StoreService.GetSmdStoreById(Utils.StrToInt(hf_in_storeId.Value, 0)));
                        var dealers = (t_smd_Dealer._DealerID.In(stores.Select(s => s.DealerID))).List<t_smd_Dealer>(Storage.Context3).ToList();
                        BusinessService.saveProcessRelation(TaskAPI, ass, null, device, null, null, stores, null, dealers);

                        if (!TaskAPI.Summary.Contains("退回"))
                        {
                            TaskAPI.Summary = "设备三方转移信息区域负责人确认 / " + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey;
                        }
                    }
                    #endregion

                    #region “Data Check”、Manager Approve步骤
                    if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                    {
                        var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                        storeMasterData.PcModel = cb_DepositConfiscated.Checked.ToString();
                        storeMasterData.DeviceEapproveSN = tb_DeviceEapproveSN.Text;
                        Storage.Save(Storage.Context1, storeMasterData);

                        // 保存变更日志
                        var changelogs = SaveChangeLog(Utils.StrToInt(chDevice, 0), ass.ID);
                        if (changelogs != null) Storage.Save(Storage.Context1, changelogs.ToArray());
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            // 将变更日志转移至smd数据库
                            var smd_changelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());

                            // 获取业务数据主键
                            var id = smd_changelogs[0].DataID;
                            // 获取原始门店数据
                            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(id, 0));
                            // 根据变更日志重新加载门店信息
                            device = DataHelper<t_smd_Device>.Reload(device, smd_changelogs);
                            if (device.StoreID != null)
                            {
                                var store = StoreService.GetSmdStoreById(device.StoreID.Value);
                                device.AuthID = store.AuthID;
                            }
                            // 更新门店信息
                            Storage.Save(Storage.Context3, device);



                            // 更新业务数据状态
                            StoreMasterDataService.UpdateFinish(TaskAPI);

                            BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                            (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident).Edit<t_StoreMasterData>(p =>
                            {
                                step = p.Step = "Finish";
                                //保存bussinesskey
                                var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                                if (masterStore.PcModel != "True")
                                {
                                    //var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                                    BusinessService.SaveSycnMappingAndBusinesskey(3, masterStore.BusinessKey);
                                }
                            });
                        }
                    }
                    #endregion
                });

                // 变更列表
                TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                flag = TaskAPI.Send();

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                else
                {
                    if (step == "Finish")
                    {
                        var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                        // 如果是空，就是手动发起的流程
                        if (string.IsNullOrEmpty(key)) return true;

                        // 三方转移自动发起流程
                        if (key == Constant.PROCESS_TRANSFER)
                        {
                            var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);


                            #region 自动启动合同变更

                            var taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                            var applicationNo = GenerateApplicationNo(taskAPI);

                            var store = StoreService.GetSmdStoreById(Utils.StrToInt(storeMasterData.MallName, 0));
                            var device = DeviceService.GetSmdDeviceById(Utils.StrToInt(storeMasterData.DispenseModel, 0));

                            //转入转出经销商相同的门店不发起合同流程(不相同才发起) 20161228
                            if (_DealerCode_in != _DealerCode_out)
                            {
                                var deviceContract = ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID) ?? new t_smd_ContractDevice { DeviceID = device.DeviceID, DeviceFixAssetNo = device.FullSetSN, StoreID = store.StoreID };
                                var deviceContractCancel = ContractDeviceService.GetContractDeviceCancel(deviceContract);
                                var deviceContractOld = ContractDeviceService.GetOldContractDevice(ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID) ?? new t_smd_ContractDevice { DeviceID = device.DeviceID });
                                if (deviceContractOld != null)
                                    deviceContractOld.DeviceCancelContractType =
                                        ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID) == null ? "" : ContractDeviceService.getContractDeviceByDeviceId(device.DeviceID).DeviceContractType;
                                Storage.Save(Storage.Context3, deviceContractOld);
                                Storage.Save(Storage.Context3, deviceContractCancel);
                                var contract = ContractService.GetContractByStoreID(Utils.StrToInt(TaskAPI.GetVariableBySingleValue("BlankVlue").Split('|')[2], 0));
                                deviceContract.StoreID = store.StoreID;
                                deviceContract = ContractDeviceService.GetNewContract(deviceContract);
                                Storage.Save(Storage.Context3, deviceContract);
                                taskAPI["ParentProcess"] = TaskAPI.Process;
                                taskAPI["ParentIncident"] = TaskAPI.Incident;
                                taskAPI["AutoBusinessKey"] = key;
                                // 选择的设备id | 转出的门店id | 转入的门店id
                                taskAPI["OldStoreID"] = TaskAPI.GetVariableBySingleValue("BlankVlue").Split('|')[1];
                                taskAPI["BlankVlue"] = TaskAPI.GetVariableBySingleValue("BlankVlue").Split('|')[2];
                                taskAPI["DeviceID"] = TaskAPI.GetVariableBySingleValue("BlankVlue").Split('|')[0];
                                taskAPI["Actions"] = "ChangeContract";
                                taskAPI["Alert"] = "此门店需要进行签署以下合同，请通知相关人员签署合同并提交总部 （可进入系统批量处理）：\n\r1、合同终止及三方转移协议";
                                taskAPI.InitAutoTask(applicationNo);
                                //taskAPI.Summary = "合同信息完善 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                                taskAPI.Summary = "合同信息完善 / " + TaskHelper.getSummary(TaskAPI.Summary);
                                taskAPI["MailSubject"] = string.Format("固定资产号：{0}--授权号：{1} -- {2}）", device.FullSetSN, store.AuthID, store.StoreType);

                                taskAPI.SetStoreDataChangeRecipient(
                                    TaskAPI.GetVariableBySingleValue("Region").ToUpper(),
                                    TaskAPI.GetVariableBySingleValue("Province"),
                                    "Contract");

                                if (taskAPI.Send())
                                {
                                    var ass = taskAPI.InitAutoAssessment();
                                    Storage.Save(Storage.Context1, ass);
                                    BusinessService.SaveChildProcess(taskAPI, ass, "active");
                                }
                            }
                            #endregion



                            if (storeMasterData.PcModel == "True")
                            {
                                #region 自动发起保证金变更

                                var region = TaskAPI.GetVariableBySingleValue("Region").ToUpper();
                                var province = TaskAPI.GetVariableBySingleValue("Province");

                                taskAPI = new TaskAPI(TaskHelper.STORE_DEPOSIT_CHANGE_TASKID);
                                applicationNo = GenerateApplicationNo(taskAPI);

                                taskAPI["ParentProcess"] = TaskAPI.Process;
                                taskAPI["ParentIncident"] = TaskAPI.Incident;
                                taskAPI["AutoBusinessKey"] = key;
                                taskAPI["BlankVlue"] = TaskAPI.GetVariableBySingleValue("BlankVlue");
                                taskAPI["Region"] = region;
                                taskAPI["Province"] = province;
                                taskAPI.InitAutoTask(applicationNo);
                                //taskAPI.Summary = "设备保证金变更 / " + TaskHelper.getSummary(TaskAPI.Summary) + _summary;
                                taskAPI.Summary = "设备保证金变更 / " + TaskHelper.getSummary(TaskAPI.Summary);
                                taskAPI.SetDepositChangeRecipient(region, province);

                                if (taskAPI.Send())
                                {
                                    var ass = taskAPI.InitAutoAssessment();
                                    Storage.Save(Storage.Context1, ass);
                                    BusinessService.SaveChildProcess(taskAPI, ass, "active");
                                }

                                #endregion
                            }
                            else
                            {
                                if (inStore.DealerID == outStore.DealerID)
                                {
                                    var deposit = DepositService.GetDeviceDeposit(device.DeviceID);
                                    if (deposit != null)
                                    {
                                        deposit.StoreID = inStore.StoreID;
                                        deposit.AuthID = inStore.AuthID;
                                        deposit.DealerId = inStore.DealerID.Value;

                                        Storage.Save(Storage.Context3, deposit);
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用Transfer.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { closeWin(); } });", true);
            }
            else
            {
                return_msg = string.IsNullOrEmpty(return_msg) ? Resources.Global.C_00_Failed : return_msg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
            }
        }

        private List<t_StoreDataChangeLog> SaveChangeLog(int deviceId, string assid)
        {
            var existing_changelogs = ChangeLogService.GetLastChangeLogs(TaskAPI);

            var device = DeviceService.GetSmdDeviceById(deviceId);
            var new_device = (t_smd_Device)device.CloneObject();
            DataHelper<t_smd_Device>.Reload(device, existing_changelogs);

            new_device.EapproveSN = tb_DeviceEapproveSN.Text;
            var storeid = Utils.StrToInt(hf_in_storeId.Value, 0);
            if (storeid > 0)
            {
                new_device.StoreID = storeid;
                if (new_device.Status != "报废")
                {
                    new_device.Status = "使用";
                }
            }

            var changelogs = DataHelper<t_smd_Device>.GetChangeLogs(device, new_device,
                new_device.GetChangeFields(), "DeviceID", UserAPI.UserFullName, assid, "ChangeDeviceTransfer");

            return ChangeLogService.GetDistinctChangeLogs(changelogs, existing_changelogs);
        }
    }
}